<template>
  <div class="variable-add">
    <a-card :title="`新增变量 - ${busiCode}`">
      <!-- 筛选条件 -->
      <div class="search-form">
        <div class="form-content">
          <a-form layout="inline">
            <a-form-item label="英文名称">
              <a-textarea
                v-model="queryParam.paramCode"
                placeholder="最大支持500个变量快速检索，变量中间用英文逗号[,]进行分割"
                :rows="3"
                :style="{ width: '500px' }"
                allowClear
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="form-actions">
          <div class="all-actions">
            <div class="search-actions">
              <a-button type="primary" @click="searchHandle">
                <a-icon type="search" />查询
              </a-button>
              <a-button @click="resetHandle">
                <a-icon type="reload" />重置
              </a-button>
            </div>
            <div class="operation-actions">
              <a-button type="primary" @click="handleAdd" :disabled="selectedRowKeys.length === 0">
                <a-icon type="plus" />添加
              </a-button>
              <a-button @click="handleCancel">
                <a-icon type="close" />取消
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        row-key="guid"
        @change="handleTableChange"
      >
        <template slot="serialNumber" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { getListAsyn, insertBatch } from '@/api/creditSetting'

const columns = [
  {
    title: '序号',
    width: 80,
    scopedSlots: { customRender: 'serialNumber' },
  },
  {
    title: '唯一标识',
    dataIndex: 'guid',
    width: 200,
  },
  {
    title: '英文名称',
    dataIndex: 'paramCode',
    width: 250,
  },
  {
    title: '中文名称',
    dataIndex: 'paramName',
    width: 300,
  },
  {
    title: '分类',
    dataIndex: 'category',
    width: 150,
  },
  {
    title: '产品',
    dataIndex: 'product',
    width: 120,
  },
]

export default {
  name: 'VariableAdd',
  data() {
    return {
      columns,
      dataSource: [],
      loading: false,
      selectedRowKeys: [],
      queryParam: {
        paramCode: '',
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      busiCode: '',
    }
  },
  created() {
    // 从路由参数获取业务编码
    this.busiCode = this.$route.query.busiCode || ''
  },
  methods: {
    // 查询
    searchHandle() {
      this.pagination.current = 1
      this.loadData()
    },
    // 重置
    resetHandle() {
      this.queryParam.paramCode = ''
      this.selectedRowKeys = []
      this.pagination.current = 1
      this.dataSource = []
    },
    // 添加
    handleAdd() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择要添加的变量')
        return
      }

      const selectedData = this.dataSource.filter(item =>
        this.selectedRowKeys.includes(item.guid)
      )

      // 将选中的变量paramCode用逗号拼接
      const paramCodes = selectedData.map(item => item.paramCode).join(',')

      const params = {
        paramCode: paramCodes,
        busiCode: this.busiCode
      }

      this.loading = true
      insertBatch(params)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success('添加成功')
            this.$router.go(-1) // 返回上一页
          } else {
            this.$message.error(res.message || '添加失败')
          }
        })
        .catch((error) => {
          console.error('添加失败:', error)
          this.$message.error('添加失败，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 取消
    handleCancel() {
      this.$router.go(-1) // 返回上一页
    },
    // 加载数据
    loadData() {
      if (!this.queryParam.paramCode.trim()) {
        this.$message.warning('请输入英文名称')
        return
      }

      const params = {
        paramCode: this.queryParam.paramCode.trim(),
        _search: '',
        nd: '',
        rows: '500',
        page: this.pagination.current.toString(),
        sidx: '',
        sord: 'asc'
      }

      this.loading = true
      getListAsyn(params)
        .then((res) => {
          if (res.code === 0) {
            this.dataSource = res.data || []
            this.pagination.total = res.data ? res.data.length : 0
          } else {
            this.$message.error(res.message || '查询失败')
            this.dataSource = []
            this.pagination.total = 0
          }
        })
        .catch((error) => {
          console.error('查询失败:', error)
          this.$message.error('查询失败，请稍后重试')
          this.dataSource = []
          this.pagination.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 表格变化
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
    },
    // 选择变化
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
  }
}
</script>

<style lang="less" scoped>
.variable-add {
  padding: 16px;

  .search-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;

    .form-content {
      margin-bottom: 12px;

      .ant-form {
        margin: 0;

        .ant-form-item {
          margin-bottom: 12px;
          margin-right: 16px;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .all-actions {
        display: flex;
        align-items: center;
        gap: 24px;
      }

      .search-actions {
        display: flex;
        gap: 8px;
      }

      .operation-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 600;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: #f5f5f5;
  }
}
</style>
